<?php
include_once 'db/db_connector.php';
/**
 * Description of DbObject
 *
 * @author chernser
 */
class DbObject {

    var $itsName; // is table name
    var $itsFields;
    var $itsKeys;
    var $itsIdFieldName;

    public function DbObject($name, $fields = null)
    {
        $this->itsName = $name;
        $this->loadDescription();

       
        if ($fields != null)
        {
            foreach ($fields as $k => $val)
            {
                $this->itsFields["$k"] = $val;
                if (isset($this->itsKeys["$k"]))
                {
                    $this->itsKeys["$k"] = $val;
                }
            }
        }
    }

    private function loadDescription()
    {
        $sql = "SHOW COLUMNS FROM ".$this->itsName;

        /* Get object description from DB */
        try {
            $result = execQuery($sql);

            $size = getResultSize($result);
            for ($i = 0; $i < $size; $i++)
            {
                $object = getRowAsArray($result);
                /* Add fields to list and initi with default value */
                $this->itsFields["$object[0]"] = $object[4];

                // if is key - add to keys
                if (strcmp(strtolower($object[3]), "pri") == 0)
                {
                    $this->itsKeys["$object[0]"] = $object[4];

                    if (strcmp(strtolower($object[5]), "auto_increment") == 0)
                    {
                        $this->itsIdFieldName = $object[0];
                    }
                }
            }

        } catch (Exception $e)
        {

            debug($e);
        }
    }

    private function getCondition($keys = null)
    {
        $condition = " WHERE ";

        if ($keys == null)
            $keys = $this->itsKeys;


        
        foreach ($keys as $k => $value) {

            if ($k == '')
                continue ;
                
            if ((!isset ($value)) && (isset($this->itsFields["$k"])))
            {
                $value = $this->itsFields["$k"];
            }

            if (ereg("([><=]+) *([0-9]+) +(AND|OR){1} +([><=]+) *([0-9]+)", $value, $regs))
            {
                $condition .= "($k $regs[1] '$regs[2]' $regs[3] $k $regs[4] '$regs[5]') AND ";
            } else if (ereg("\[(.+)\]", $value, $regs))
            {
                $ar = split(" +", trim($regs[1]));
                foreach ($ar as $val)
                {
                    $condition .= " $k = '$val' OR ";
                }
            } else
            {
                $condition .= $k." = '".$value."' AND ";
            }

        }

        $length = strlen($condition) - 4;
        return substr($condition, 0, $length);
    }

    public function setKey($name, $value)
    {
        if (isset($this->itsKeys["$name"]))
        {
            $sql = "UPDATE ".$this->itsName." SET ".$name;
            $sql .= " = '$value' ";
            $sql .= $this->getCondition();

            $result = execQuery($sql);
        }

        $this->itsFields["$name"] = $value;
        $this->itsKeys["$name"] = $value;
    }

    public function setField($name, $value)
    {
        $sql = "UPDATE ".$this->itsName." SET ".$name;
        $sql .= " = '$value' ";
        $sql .= $this->getCondition();

        $result = execQuery($sql);
        lastSqlError(); // TODO: remove
        $this->itsFields["$name"] = $value;
        if (isset($this->itsKeys["$name"]))
        {
            $this->itsKeys["$name"] = $value;
        }
    }

    public function getField($name)
    {
        return $this->itsFields["$name"];
    }


    public function Load($keys = null)
    {
        $sql = "SELECT * FROM ".($this->itsName).$this->getCondition($keys);
        $result = execQuery($sql);
        lastSqlError(__FILE__, __LINE__); // todo: remove
        $this->itsFields = getRowAsAssoc($result);

        foreach ($this->itsKeys as $k => $value) {
            $this->itsKeys["$k"] = $this->itsFields["$k"];
        }

        if (getResultSize($result) > 0)
            return true;

        
        return false;
    }

    public function Delete($keys = null)
    {
        $sql = "DELETE FROM ".$this->itsName
        .$this->getCondition($keys);
        execQuery($sql);
    }

    public function Create($fields = null)
    {
        $sql = "INSERT INTO ".$this->itsName;

        if ($fields != null)
        {
            $field_list = "";
            $values = "";

            
            foreach ($fields as $k => $val)
            {
                $field_list .= "$k, ";
                $values .= " '$val', ";
            }

            $field_list = substr($field_list, 0, strlen($field_list) - 2);
            $values = substr($values, 0, strlen($values) - 2);

            $sql .= " ($field_list) VALUES ($values)";
        } else
        {
            $sql .= " () VALUES ()";
        }

        
        execQuery($sql);        
        lastSqlError(__FILE__, __LINE__); // todo: remove
        $this->setKey($this->itsIdFieldName, getLastInsertId());
        $this->Load(null);
    }

    public function LoadList($keys = null)
    {
        $sql = "SELECT * FROM ".$this->itsName;
        $list = array();

        if (isset($keys))
        {
            $sql .= $this->getCondition($keys);
        }

        
        $result = execQuery($sql);
        lastSqlError(__FILE__, __LINE__); // todo: remove

        $size = getResultSize($result);
        for ($i = 0; $i < $size; $i++)
        {
            $object = getRowAsAssoc($result);
            $class = get_class($this);

            $list[$i] = new $class($this->itsName, $object);
        }

        return $list;
    }

}


?>
